package cn.edu.ctbu.datajpa01.restcontroller;

import cn.edu.ctbu.datajpa01.domain.Student;
import cn.edu.ctbu.datajpa01.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static java.lang.String.valueOf;

@RestController
@RequestMapping(value = "/webapi/student")
public class StudentRestController {
    @Autowired
    StudentService sudentService;

    @GetMapping("list")
    public List<Student> GetAll(){
        return sudentService.findAll();
    }
    @GetMapping(value = "{id}")
    public Student GetById(@PathVariable Integer id){return sudentService.findById(id);}

    @GetMapping(value = "name/{name}")
    public Student GetByName(@PathVariable String name){
        List<Student> students=sudentService.findAll();//获取所有学生信息
        for (int i = 0; i < students.size(); i++) {
            String tempnmae=String.valueOf(students.get(i).getName());//获取每个学生姓名，并于name对比
            if (name.equals(tempnmae)) {
                return students.get(i);//找到就返回对应学生对象
            }
        }
        return null;//没找到
    }

    @DeleteMapping(value = "delete/{id}")
    public  boolean DeleteById(@PathVariable Integer id){sudentService.delete(id);return  true;}
    @PostMapping(value = "add")
    public Integer Add(@RequestBody Student student){
        sudentService.save(student);
        return student.getId();}
    @PutMapping(value = "updata")
    public Integer Updata(@RequestBody Student student){
        sudentService.save(student);
        return student.getId();
    }
    @PostMapping("/insert")
    public Student insert(@RequestBody Student student){
        Student student1=sudentService.insert(student);
        return student1;
    }

}

